package observer

import "fmt"

// item 具体主体
type item struct {
	observerList []observer
	name         string
	inStock      bool
}

func NewItem(name string) *item {
	return &item{
		observerList: nil,
		name:         name,
		inStock:      false,
	}
}

func (i *item) UpdateAvailability()  {
	fmt.Printf("Item %s is now in stock\n", i.name)
	i.inStock = true
	i.notifyAll()
}

func (i *item) Register(observer observer) {
	i.observerList = append(i.observerList, observer)
}

func (i *item) Deregister(observer observer) {
	i.observerList = removeFromSlice(i.observerList, observer)
}

func (i *item) notifyAll() {
	for _, observer := range i.observerList {
		observer.Update(i.name)
	}
}

func removeFromSlice(observerList []observer, observerToRemove observer) []observer {
	observerListLength := len(observerList)
	for i, observer := range observerList {
		if observerToRemove.GetID() == observer.GetID() {
			observerList[observerListLength-1], observerList[i] = observerList[i], observerList[observerListLength-1]
			return observerList[:observerListLength-1]
		}
	}
	return observerList

}


